package com.mmall.service.impl;

import com.mmall.common.DataSource;
import com.mmall.common.ParamCommon;
import com.mmall.common.ResponseService;
import com.mmall.common.ResultCode;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.CacheUtil;
import com.mmall.util.Md5Utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;


@Service
public class UserServiceImpl implements IUserService {

    private static final Logger  log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    UserMapper userMapper;

    @Override
    public ResponseService login(String username, String password) {
        if(log.isDebugEnabled()){
            log.debug("");
        }
        if(StringUtils.isBlank(username)){
            return ResponseService.creteResponseFail(ResultCode.USERNAME_NO_EXIST.getStatus(),ResultCode.USERNAME_NO_EXIST.getMsg());
        }
        if(StringUtils.isBlank(password)){
            return ResponseService.creteResponseFail(ResultCode.PASSWD_ERROR.getStatus(),ResultCode.PASSWD_ERROR.getMsg());
        }


        int count = userMapper.checkUserName(username);
        if(count == 0){
            return ResponseService.creteResponseFail(ResultCode.USERNAME_NO_EXIST.getStatus(),ResultCode.USERNAME_NO_EXIST.getMsg());
        }
        password = Md5Utils.MD5EncodeUtf8(password);
        User user = userMapper.getUserByUserNameAndPass(username,password);
        if(user ==null ){
            return ResponseService.creteResponseFail(ResultCode.PASSWD_ERROR.getStatus(),ResultCode.PASSWD_ERROR.getMsg());
        }
        // 安全起见 用户密码和问题答案为空
        user.setPassword(StringUtils.EMPTY);
        user.setAnswer(StringUtils.EMPTY);
        return ResponseService.creteResponseSuccessByData(user);
    }

    @Override
    public ResponseService register(User user) {
        if(user ==null || StringUtils.isBlank(user.getUsername())
                || StringUtils.isBlank(user.getPassword())
                || StringUtils.isBlank(user.getEmail())
                || StringUtils.isBlank(user.getPhone())){
            return ResponseService.creteResponseFail(ResultCode.PASSWD_ERROR.getStatus(),ResultCode.PASSWD_ERROR.getMsg());
        }

        int count = userMapper.checkUserName(user.getUsername());
        if(count != 0){
            return ResponseService.creteResponseFail(ResultCode.USERNAME_EXIST.getStatus(),ResultCode.USERNAME_EXIST.getMsg());
        }
        int countEmail = userMapper.checkEmail(user.getEmail());
        if(countEmail != 0){
            return ResponseService.creteResponseFail(ResultCode.EMAIL_EXIST.getStatus(),ResultCode.EMAIL_EXIST.getMsg());
        }

        user.setRole(ParamCommon.Role.ROLE_ORDINARY);
        user.setPassword(Md5Utils.MD5EncodeUtf8(user.getPassword()));
        int i = userMapper.insertSelective(user);
        if(i==0){
            return ResponseService.creteResponseFailMsg("注册失败！");
        }
        user.setPassword(StringUtils.EMPTY);
        return ResponseService.creteResponseSuccessMsg("注册成功！");
    }

    @Override
    public ResponseService checkValid(String str, String type) {
        if(StringUtils.isBlank(str)){
            return ResponseService.creteResponseFailByCode(ResultCode.PARAM_ERROR);
        }
        if(ParamCommon.Type.TYPE_EMAIL.equals(type)){
            // 检验邮箱
            int count = userMapper.checkEmail(str);
            if(count>0){
                return ResponseService.creteResponseFailByCode(ResultCode.EMAIL_EXIST);
            }
        }else if(ParamCommon.Type.TYPE_USERNAME.equals(type)){
            // 检验用户名
            int count = userMapper.checkUserName(str);
            if(count>0){
                return ResponseService.creteResponseFailByCode(ResultCode.USERNAME_EXIST);
            }
        }else{
            // 类型错误
            return ResponseService.creteResponseFailByCode(ResultCode.TYPE_ERROR);
        }
        return ResponseService.creteResponseSuccess();
    }

    @Override
    public ResponseService forGetQuestion(String username) {
        if(StringUtils.isBlank(username)){
            return ResponseService.creteResponseFailByCode(ResultCode.PARAM_ERROR);
        }
        String question = userMapper.getQuestion(username);
        if(StringUtils.isBlank(question)){
            return ResponseService.creteResponseFailMsg("该用户未设置找回密码问题。");
        }
        return ResponseService.creteResponseSuccessByData(question);
    }

    @Override
    public ResponseService CheckAnswer(String username, String question, String answer) {
        int count = userMapper.CheckAnswer(username,question,answer);
        if(count==0){
            return ResponseService.creteResponseSuccessMsg("提示问题回答错误");
        }else{
            // 生成token
            String token = UUID.randomUUID().toString();
            // 存入缓存
            CacheUtil.setLoadCache(ParamCommon.KEY_LOCADING_PREFIX + username ,token);
            return ResponseService.creteResponseSuccessByData(token);
        }
    }

    @Override
    public ResponseService resetPasswordByUserName(String username, String passwordNew, String forgetToken) {
        if(StringUtils.isBlank(username)){
            return ResponseService.creteResponseFail(ResultCode.USERNAME_NO_EXIST.getStatus(),ResultCode.USERNAME_NO_EXIST.getMsg());
        }
        int count = userMapper.checkUserName(username);
        if(count == 0){
            return ResponseService.creteResponseFail(ResultCode.USERNAME_NO_EXIST.getStatus(),ResultCode.USERNAME_NO_EXIST.getMsg());
        }
        String oldToken = CacheUtil.getLoadCache(ParamCommon.KEY_LOCADING_PREFIX + username);
        if(StringUtils.equals(oldToken,forgetToken)){
            passwordNew = Md5Utils.MD5EncodeUtf8(passwordNew);
            int resultCount = userMapper.resetPasswordByUserName(username, passwordNew);
            if(resultCount>0){
                return ResponseService.creteResponseSuccess();
            }else{
                return ResponseService.creteResponseFailMsg("修改密码失败.");
            }
        }
        return ResponseService.creteResponseFailMsg("操作超时 ，请重新操作.");
    }

    @Override
    public ResponseService resetPasswordByUsernamePass(Integer userId, String passwordNew, String passwordOld) {
        passwordNew = Md5Utils.MD5EncodeUtf8(passwordNew);
        passwordOld = Md5Utils.MD5EncodeUtf8(passwordOld);
        // 根据用户获取用户密码   可能被试出来，所以根据UserId 和 密码 count 是否存在
        int resultCount = userMapper.checkPasswd(userId, passwordOld);
        if(resultCount > 0){
            resultCount = userMapper.resetPasswordByID(userId,passwordNew);
            if(resultCount > 0){
                return ResponseService.creteResponseSuccessMsg("修改密码成功!");
            }else{
                return ResponseService.creteResponseFailMsg("修改密码失败。");
            }
        }else{
            return ResponseService.creteResponseFailMsg("旧密码错误");
        }
    }

    @Override
    public ResponseService updateUserInfo(User user) {
        // 检查用户更新信息中的email是否存在
        int count = userMapper.checkEmailByUserId(user.getId(), user.getEmail());
        if(count > 0 ){
            return ResponseService.creteResponseFailMsg("用户邮箱已存在,请修改邮箱后重试。");
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());
        int resultCount = userMapper.updateByPrimaryKeySelective(user);
        if(resultCount>0){
            return ResponseService.creteResponseSuccess("更新个人信息成功。",user);
        }else{
            return ResponseService.creteResponseFailMsg("更新个人信息失败！");
        }
    }

}
